#pragma once
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <unistd.h>
#include <vector>
#include <functional>
#include "Log.hpp"
#include "commd.hpp"
#include "nocopy.hpp"
#include "InetAddr.hpp"
#include "threadpool.hpp"
#include "LockGuard.hpp"
using namespace std;


using func = function<void()>;


class UdpServer : public nocopy {
public :
    UdpServer(const uint16_t port) 
        :_port(port)
    {
        // 初始化锁
        pthread_mutex_init(&_user_mutex, nullptr);
    }
    void Init() {
        // 1、创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0) {
            // 创建套接字失败
            lg.LogMessage(Fatal, "create socket error, error code: %d, error string: %s", errno, strerror(errno));
            exit(Socket_Err);
        }
        // 创建套接字成功
        lg.LogMessage(Debug, "create socket success, sockfd: %d", _sockfd);

        // 2、绑定

        // 先填充本地网络信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        // 绑定
        int n = ::bind(_sockfd, (struct sockaddr*)&local, sizeof local);
        if (n != 0) {
            // 绑定失败
            lg.LogMessage(Fatal, "bind error, error code: %d, error string: %s", errno, strerror(errno));
            exit(Bind_Err);
        }
        // 绑定成功
        lg.LogMessage(Debug, "bind sucess");

        // 获取线程池单例
        threadpool<func>::GetInstance()->Start();
    }

    // 添加在线用户
    void AddOnlineUser(InetAddr& addr) {
        {
            // 先加锁
            LockGuard lock(&_user_mutex);
            for (auto& user : _online_user) {
                if (user == addr) {
                    return;
                }
            }
            _online_user.push_back(addr);
            lg.LogMessage(Debug, "add user: %s success", addr.get_info().c_str());
        }
    }

    void Route(int sockfd, const string& message) {
        {
            // 先加锁
            LockGuard lock(&_user_mutex);
            for (auto& user : _online_user) {
                int n = sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&user.addr(), sizeof user.addr());
                if (n == -1) {
                    cerr << "发送失败" << endl;
                }
                lg.LogMessage(Debug, "server send message to %s", user.get_info().c_str());
            }
        }

    }
    
    void Start() {
        char buffer[1024];
        struct sockaddr_in peer; // 接收客户端信息
        memset(&peer, 0, sizeof peer);
        socklen_t len = sizeof peer; 
        while (true) {
            // 先接收消息
            int n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
            if (n > 0) {
                buffer[n] = '\0';
                InetAddr addr(peer);
                AddOnlineUser(addr);

                // 回发消息
                string server_echo = addr.get_info() + "# ";
                server_echo += buffer;
                func task = bind(&UdpServer::Route, this, _sockfd, server_echo);
                threadpool<func>::GetInstance()->Push(task);
            } else {
                break;
            }

        }

    }
    ~UdpServer() {
        // 销毁锁
        pthread_mutex_destroy(&_user_mutex);
    }
private :
    int _sockfd;
    uint16_t _port;
    vector<InetAddr> _online_user; // 在线用户列表
    pthread_mutex_t _user_mutex;
};